package cn.tedu.tmall.basic.service.impl;

import cn.tedu.tmall.basic.dao.cache.repository.IDistrictCacheRepository;
import cn.tedu.tmall.basic.dao.persist.repository.IDistrictRepository;
import cn.tedu.tmall.common.pojo.po.DistrictSimplePO;
import cn.tedu.tmall.basic.service.IDistrictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 处理省市区数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 3.0
 */
@Slf4j
@Service
public class DistrictServiceImpl implements IDistrictService {

    @Autowired
    private IDistrictRepository districtRepository;
    @Autowired
    private IDistrictCacheRepository districtCacheRepository;

    public DistrictServiceImpl() {
        log.debug("创建业务类对象：DistrictServiceImpl");
    }

    @Override
    public List<DistrictSimplePO> listByParent(Long parentId) {
        log.debug("开始执行【根据父级查询子级地区列表】的业务，参数：{}", parentId);
        return districtRepository.listByParent(parentId);
    }

    @Override
    public void rebuildCache() {
        districtCacheRepository.deleteAll();

        Long parentId = 0L;
        List<DistrictSimplePO> list = districtRepository.listByParent(parentId);

        for (DistrictSimplePO districtSimplePO : list) {
            districtCacheRepository.save(districtSimplePO);
        }

        districtCacheRepository.saveListByParent(parentId, list);
        for (DistrictSimplePO listItem : list) {
            callListRecursion(listItem);
        }
    }

    /**
     * 递归得到各地区的子级列表数据
     *
     * @param district 地区数据
     */
    private void callListRecursion(DistrictSimplePO district) {
        Long districtId = district.getId();
        List<DistrictSimplePO> list = districtRepository.listByParent(districtId);
        if (list.size() > 0) {
            districtCacheRepository.saveListByParent(districtId, list);
            for (DistrictSimplePO districtSimplePO : list) {
                districtCacheRepository.save(districtSimplePO);
                callListRecursion(districtSimplePO);
            }
        }
    }

}
